import os, random, requests
import threadpool
import threading
import time

# from requests_toolbelt.multipart.encoder import MultipartEncoder
def http_test(path0,file_stream):
    name = os.path.basename(path0).split(".")[-1]
    flag = ''
    if name == 'png':
        flag = 'image/png'
    elif name == 'jpg':
        flag = 'image/jpeg'
    else :
        print(path0)
        return
    url = 'http://123.57.182.5:8080/home/CapRecognitionInterface'
    # headers = {
    #     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
    #                   'Chrome/68.0.3440.106 Safari/537.36',
    #     'Referer': url
    #     }
    files= {'bigType': (None, '7'),
            'smallType': (None, '1'),
            'para1': (None,''),
            'para2': (None,''),
            'imgData': (os.path.basename(path0),
                       file_stream,
                        flag)
     }

    r = requests.post(url, files=files)
    print(r.text)

    mutex.acquire(timeout=10)
    with open('test_out.txt', 'a') as f:
        f.write(path0  + '  '+ str(time.time()) + ' '*10 + r.text + '\n')
        f.close()
        count_all +=1
    mutex.release()

def main():
    start = time.time()
    dir_path = r'C:\Users\vanlance\Desktop\3'
    # mutex = threading.Lock()
    pool = threadpool.ThreadPool(4)
    func_var1 = [os.path.join(dir_path,p) for p in os.listdir(dir_path)]
    func_var2 = [ open(p, 'rb') for p in func_var1]
    func_var = [[path,file_stream] for a,b in zip(func_var1, func_var2)]
    other = [None for i in range(len(func_var1))]
    requests_p = threadpool.makeRequests(http_test, zip(func_var,other))
    [pool.putRequest(req) for req in requests_p]
    pool.wait()
    print(time.time() - start)

def download_img(txt_url, save_dir):
    with open(txt_url, "r") as rf:
        for idx,line in enumerate(rf.readlines()):
            url_ = line.replace("\r\n","").replace("\n","")
            req = requests.get(url_)
            with open(save_dir + os.sep + "{}.jpg".format(idx), "wb") as wf:
                wf.write(req.content)
                

if __name__ == "__main__":
    # txt_url = r"E:\work\data\data\2020_03\威瑟兰斯样本测试\urls.txt" 
    # save_dir = r"E:\work\data\data\2020_03\威瑟兰斯样本测试\url_img"
    # download_img(txt_url, save_dir)

    url = "http://chiheng.haikewulian.com/#/printcode?id=9059&table=bill&type=all"
    res = requests.get(url)
    print(res.text)
